'use strict';
const uniID = require('uni-id-common');
const db = uniCloud.database();
exports.main = async (event, context) => {
    let body = event;
    if (event.body != undefined) {
        body = JSON.parse(event.body)
    }
    const uniIDIns = uniID.createInstance({ context });
    const { sToken, cToken } = body;
    
    // Check if both tokens are provided
    if (sToken !== undefined && cToken !== undefined) {
        return {
            code: 400, // Bad Request
            message: '不能同时传入sToken和cToken'
        }
    }
    
    // Check if no token is provided
    if (sToken === undefined && cToken === undefined) {
        return {
            code: 400, // Bad Request
            message: '缺少必要参数'
        }
    }
    
    try {
        let uid;
        let role;
        
        // Check sToken
        if (sToken) {
            const tokenInfo = await uniIDIns.checkToken(sToken);
            if (tokenInfo.errCode) {
                return {
                    code: 403, // Unauthorized
                    message: 'sToken验证失败',
                    err: tokenInfo.errCode
                }
            }
            uid = tokenInfo.uid;
            role = 'supervisor';
        }
        
        // Check cToken
        if (cToken) {
            const tokenInfo = await uniIDIns.checkToken(cToken);
            if (tokenInfo.errCode) {
                return {
                    code: 403, // Unauthorized
                    message: 'cToken验证失败',
                    err: tokenInfo.errCode
                }
            }
            uid = tokenInfo.uid;
            role = 'consultant';
        }
        
        // Query the sc_relations table
        const collection = db.collection('sc_relations');
        let query;
        
        if (role === 'supervisor') {
            query = collection.where({
                supervisor_id: uid
            });
        } else {
            query = collection.where({            
				consultant_id: uid
            });
        }
        
        const res = await query.get();
        
        if (res.data.length === 0) {
            return {
                code: 404, // Not Found
                message: '未找到相关记录'
            }
        }
        
        return {
            code: 200, // Success
            message: '查询成功',
            data: res.data
        }
        
    } catch (error) {
        console.error(error);
        return {
            code: 500, // Internal Server Error
            message: '服务器内部错误',
            error: error.message
        }
    }
};